package sensor;

import grammer.components.ObjectEnum;
import houseHold.HouseHoldObject;
import houseHold.Room;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;

import timer.Time;
import timer.Timer;
import weather.CurrentWeather;
import constants.Constants;

public class LumenCalculator {
	private static HashMap<Integer, Integer> list = new HashMap<Integer, Integer>();

	public static double compute(Room r, int time) {
		double candela = 0;
		double tval = 0;
		if (time < Time.dawnTime || time > Time.duskTime)
			tval = 0;
		else {
			if (time < Time.getMidDay())
				tval = time-Time.dawnTime;
			else{
				tval =Time.duskTime-time;
			}
			tval = tval / Time.getMidDay();
		}
		candela = 8000 * tval * tval * CurrentWeather.getInstance().getWeatherCoef()
				+ getLightLum(r);
		double surface = r.getWidth() + r.getLength() / 200;
		return candela / surface;
	}

	public static int getAverage(int con) {
		initList();
		int average = 0;
		Set<Integer> ks = list.keySet();
		Iterator<Integer> it = ks.iterator();
		int curr = 25;
		while (it.hasNext()) {
			int last = curr;
			curr = it.next();
			if (curr >= con) {
				average = (list.get(last) + list.get(curr)) / 2;
			}
		}
		return average;
	}

	private static int getLightLum(Room r) {
		HouseHoldObject light = r.getItemByType(ObjectEnum.LIGHT);
		int lc = 0;
		HouseHoldObject tv = r.getItemByType(ObjectEnum.TELEVISION);
		int tvc = 0;
		HouseHoldObject cpu = r.getItemByType(ObjectEnum.COMPUTER);
		int cpuc = 0;
		if (light != null)
			if (light.isActive())
				lc = light.getConsumption();
		if (tv != null)
			if (tv.isActive())
				tvc = tv.getConsumption();
		if (cpu != null)
			if (cpu.isActive())
				cpuc = cpu.getConsumption();
		int res = cpuc / 2 + tvc / 2 + getAverage(lc);
		int variable = res / 25;
		int avg = Constants.rd.nextInt(variable);
		boolean sw = Constants.rd.nextBoolean();
		if (sw)
			avg = avg * (-1);
		return res + avg;
	}

	private static void initList() {
		list.put(5, 25);
		list.put(15, 110);
		list.put(25, 200);
		list.put(35, 350);
		list.put(40, 500);
		list.put(50, 700);
		list.put(55, 800);
		list.put(60, 850);
		list.put(65, 1000);
		list.put(70, 1100);
		list.put(75, 1200);
		list.put(90, 1450);
		list.put(95, 1600);
		list.put(100, 1700);
		list.put(135, 2350);
		list.put(150, 2850);
		list.put(200, 3900);
		list.put(300, 6200);
	}
}
